<?php
/**
 * Created by PhpStorm.
 * User: wangxj
 * Date: 2017/06/21
 */

namespace App\Helper;

use Carbon\Carbon;

class CommonHelper
{
    const APP_NAME = '';

    const ACCOUNT_NAME = "中医在线健康助手";

    public static function object2array($object)
    {
        $arr = json_decode(json_encode($object), true);

        return $arr;
    }

    public static function now()
    {
        return date('Y-m-d H:i:s', time());
    }

    public static function timeAPM()
    {
        //计算时间
        $houre       = date('H');
        $currentDate = date('Y年m月d日');
        if ($houre < 11)
        {
            $currentDate .= '上午';
        }
        else
        {
            $currentDate .= '下午';
        }

        return $currentDate;
    }

    // 取得年龄
    public static function getAge($birthday)
    {
        if (!isset($birthday) || empty($birthday) || $birthday == '1000-01-01' || $birthday == '0000-00-00')
        {
            return '未填写';
        }

        $datetime_start = new \DateTime($birthday);
        $datetime_end   = new \DateTime(today());
        $dateInterval   = $datetime_start->diff($datetime_end);

        $y = $dateInterval->y;
        $m = $dateInterval->m;
        $d = $dateInterval->d;

        if ($y > 0)
        {
            if ($y < 3 && $m > 0)
            {
                return $y . '岁' . $m . '个月';
            }
            return $y . '岁';
        }
        elseif ($m > 0)
        {
            return $m . '个月';
        }
        elseif ($d > 0)
        {
            return $d . '天';
        }
        else
        {
            return '0岁';
        }
    }

    // 取得年龄
    public static function getAgeAt($birthday, $at_day)
    {
        if (!isset($birthday) || empty($birthday) || $birthday == '1000-01-01' || $birthday == '0000-00-00')
        {
            return '未填写';
        }

        if (empty($at_day))
        {
            $at_day = Carbon::now();
        }

        $start = new Carbon($birthday);
        $end   = new Carbon($at_day);

        $y = $start->diffInYears($end);
        $m = $start->diffInMonths($end);
        $d = $start->diffInDays($end);

        if ($y > 0)
        {
            if ($y < 3 && $m > 0)
            {
                return $y . '岁' . $m . '个月';
            }
            return $y . '岁';
        }
        elseif ($m > 0)
        {
            return $m . '个月';
        }
        elseif ($d > 0)
        {
            return $d . '天';
        }
        else
        {
            return '0岁';
        }
    }

    // post请求
    public static function syncUserInfo($doctor)
    {
        if ($doctor->sex == 1)
        {
            $gender = 'male';
        }
        elseif ($doctor->sex == 2)
        {
            $gender = 'female';
        }
        else
        {
            $gender = 'secret';
        }
        // tcmmooc医生信息同步
        $inqData['truename']       = $doctor->name;
        $inqData['verifiedMobile'] = $doctor->mobile;
        $inqData['gender']         = $gender;
        $inqData['company']        = $doctor->company;
        $inqData['department']     = $doctor->department;
        $ret                       = self::request('POST', config('app.tcmmooc_url') . '/mapi_v3/User/setTcmUser', array('data' => json_encode($inqData)));
    }

    public static function request($method, $url, $params = array(), $conditions = array())
    {
        $conditions['userAgent']      = isset($conditions['userAgent']) ? $conditions['userAgent'] : '';
        $conditions['connectTimeout'] = isset($conditions['connectTimeout']) ? $conditions['connectTimeout'] : 10;
        $conditions['timeout']        = isset($conditions['timeout']) ? $conditions['timeout'] : 10;

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_USERAGENT, $conditions['userAgent']);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $conditions['connectTimeout']);
        curl_setopt($curl, CURLOPT_TIMEOUT, $conditions['timeout']);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 1);

        if ($method == 'POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            //TODO
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        }
        elseif ($method == 'PUT')
        {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));
        }
        elseif ($method == 'DELETE')
        {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));
        }
        elseif ($method == 'PATCH')
        {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));
        }
        else
        {
            if (!empty($params))
            {
                $url = $url . (strpos($url, '?') ? '&' : '?') . http_build_query($params);
            }
        }

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);

        $response = curl_exec($curl);
        $curlinfo = curl_getinfo($curl);

        $header = substr($response, 0, $curlinfo['header_size']);
        $body   = substr($response, $curlinfo['header_size']);

        curl_close($curl);

        if (empty($curlinfo['namelookup_time']))
        {
            return array();
        }

        if (isset($conditions['contentType']) && $conditions['contentType'] == 'plain')
        {
            return $body;
        }

        $body = json_decode($body, true);
        return $body;
    }

    // 数据转换
    public static function xml_to_data($xml)
    {
        if (!$xml)
        {
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }

    public static function genAdminPrintUrl($name, $para)
    {
        $url = '/' . config('admin.route.prefix') . "/report/print/" . $name;
        if (!empty($para))
        {
            $url .= '?' . $para;
        }

        return $url;
    }

    public static function clearArrayNullValue($array)
    {
        if (empty($array))
        {
            return [];
        }

        if (($key = array_search(null, $array)) !== false)
        {
            unset($array[$key]);
        }

        return array_values($array);
    }

    public static function clearNull($array)
    {
        if (empty($array))
        {
            return [];
        }

        $new = [];
        foreach ($array as $value)
        {
            if (!empty($value))
            {
                $new[] = $value;
            }
        }

        return $new;
    }

    //字符串处理
    public static function strSegmentation($str)
    {
        //需要替换的字符
        $order = array("，", "；", "。", "、");
        //替换的值
        $replace = '<br/>';
        //替换字符串中所有需要替换的字符
        $newstr = str_replace($order, $replace, $str);
        //根据替换值拆成数组
        $newstr = explode($replace, $newstr);

        $specialty = [];
        foreach ($newstr as $v) {
            if (!empty($v)) {
                $specialty[] = $v;
            }
        }

        return $specialty;
    }

    //换行符处理
    public static function clearLine($str)
    {
        //需要替换的字符
        $order = array(
            "\r\n",
            "\n",
            "\r"
        );
        //替换的值
        $replace = '<br/>';
        //替换字符串中所有需要替换的字符
        $newstr = str_replace($order, $replace, $str);
        //根据替换值拆成数组
        $newstr = explode($replace, $newstr);

        $specialty = [];
        foreach ($newstr as $v)
        {
            if (!empty($v))
            {
                $specialty[] = $v;
            }
        }

        return $specialty;
    }

    //获取医院级别
    public static function getHospitalLevel($level)
    {
        $hospital = [
            0 => "知名医院",
            1 => "三甲医院",
            2 => "三级医院",
            3 => "二甲医院",
            4 => "二级医院"
        ];

        return $hospital[$level];
    }

    public static function getNumber($num)
    {
        if ($num >= 10000)
        {
            $number = round($num / 10000, 1) . '万';
        }
        else
        {
            $number = $num;
        }
        return $number;
    }

    public static function isDevelopEnv()
    {
        if (strpos(config('app.url'), 'wz.tcmlive.com') === false)
        {
            return true;
        }

        return false;
    }
}